#include "device_type.h"
#ifdef SM_TEMPHUMI
#include "app_api.h"
#include "app_log.h"
#include "app_cli_cmd.h"
#include "bsp_gpio.h"
#include "app_button.h"
#include "em_i2c.h"
//#include "app_led.h"  //温湿度探测器无Led灯
#include "bsp_iadc.h"
#include "em_emu.h"
#include "softwareMultiTimer.h"
#include "device.h"
#include "bsp_system.h"
#include "net_protocol.h"
#include "app_key_value.h"
#include "bsp_rmu.h"
#include "bsp_wdog.h"
#include "RBFVersion.h"
#include "git_version.h"
#include "bsp_SHT20.h"
#include "bsp_BL55072A.h"
#include "net_packet.h"
//#include "sl_udelay.h"
#include "net_logout.h"

#define DEVICE_TX_POWER_DEFAULT  (160) //温湿度使用16dbm功率
#define DEVICE_CTUNE_DEFAULT     (125)
#define DEVICE_LFXO_CTUNE_DEFAULT (40)
#define IADC_TIMER_INTERVAL      (240)  //s
#define APP_MAJOR_VERSION        (1)
#define APP_MINOR_VERSION        (1)
#define APP_STAGE_VERSION        (2) //max 255

#define BAT_THRESHOLD_100       3900// 3.9v 1.3*3
#define BAT_THRESHOLD_75        3450// 3.45v 1.15*3
#define BAT_THRESHOLD_50        3000// 3.00v 1.00*3
#define BAT_THRESHOLD_25        2550// 2.55v 0.85*3 <2550表示电池0格

#define RSSI_THRESHOLD_4        -78//
#define RSSI_THRESHOLD_3        -84//
#define RSSI_THRESHOLD_2        -90//
#define RSSI_THRESHOLD_1        -127// <-127即-128表示无信号
/*******************更新记录**************************************
* V0.0.1 初始版本
* V0.0.2 温湿度物模型更新，湿度字段拓展2字节
**********************************************************/
#define SENSOR_VERSION           ((APP_MAJOR_VERSION << 16)|(APP_MINOR_VERSION<<8)|(APP_STAGE_VERSION))

static int16_t s_lastReportTemp = 0; //在每次无线上报时更新
static uint8_t s_tempReportInterval = 50;// 默认最大档位5℃
static int16_t s_lastReportHumi = 0;
static uint8_t s_humiReportInterval = 100;// 默认最大档位10%

static bool isLocalRssiIndicate = true;
static bool isLocalBattIndicate = true;

static uint8_t s_option[3] = {0x00};//保存Option

static void setTxpowerDefaule(void);
static void setCtuneDefaule(void);
static void setLfxoCtuneDefaule(void);
static void gpio_state_change_handler(void);
static void SM_button_init(void);
static void SM_iadc_init(void);
static void printSoftWareInformation(void);
static void iadcTimerCallback(MultiTimer* timer, void *userData);
static uint8_t device_TempHumi_get(uint8_t *buffer);

void lcdIndicateInit()
{
  getThisParam(ENpbyOption, s_option); //从NVM恢复option
  if(!isregeist()){ //未注册时，初始化option字段
      s_option[2] = 0x00;
    if(RF_FREQ_915MHZ == getDeviceRfFreq()){
        s_option[2] |= 0x01; //本地或远程未配置时，915频段默认使用华氏度
      }
  }

  s_option[1] = 0x00; //信号强度和电量本地展示
  recv_option_key_value_handler(s_option);//初始化option配置项
}

int netCallback(NET_UP_EVENT_TYPE_EN type, bool isSucced, int8_t rssi, void *pData)
{
  (void)pData;
  (void)type;
  static uint8_t sFailCnt = 0;
  if(isSucced)
  {
      sFailCnt = 0;
      if(isLocalRssiIndicate)
      {
        if(rssi > RSSI_THRESHOLD_4)
          {
            LcdRssiLevelSet(4);
          }
        else if(rssi > RSSI_THRESHOLD_3)
          {
            LcdRssiLevelSet(3);
          }
        else if(rssi > RSSI_THRESHOLD_2)
          {
            LcdRssiLevelSet(2);
          }
        else if(rssi > RSSI_THRESHOLD_1)
          {
            LcdRssiLevelSet(1);
          }
      }
  }
  else
  {
    sFailCnt++;
    if(sFailCnt >= 2)
    {
        LcdRssiLevelSet(0);
    }
  }
  return 0;
}

/**
 * @brief: 门磁项目相关外设初始化
 * */
void SM_main(void)
{
  uint32_t pre_ticks = 0;
  SM_iadc_init();//初始化获取电池电压等信息
  ReadShtC3();
  setTxpowerDefaule();
  setCtuneDefaule();
  setLfxoCtuneDefaule();
  printSoftWareInformation();
  SM_button_init();
  startWatchDogTimer();
  lcdIndicateInit();
  BL55072A_Init();
  ReadShtC3();
  //sl_udelay_wait(30000);//延时30ms 确保成功读到温湿度，以及电池电压采集
  pre_ticks = READ_SYS_RTC_COUNT();
  while(1){
      if((READ_SYS_RTC_COUNT() - pre_ticks) >= 1147){ //35ms
          break;
      }
  }
  ReadShtC3();//35ms延时 才能成功读到温度
  iadcTimerCallback(NULL,NULL);//初始化获取电池电压等信息
  BL55072A_DisTR();
  reg_net_upload_result(netCallback);//
}

void checkTempHumiChanged()
{
  int16_t subTemp = 0;
  int16_t subHumi = 0;
  if(LCD_DIS_Flag)
  {
      subTemp = getCurrentTemp() - s_lastReportTemp;
      subHumi = getCurrentHumi() - s_lastReportHumi;
      if( (subTemp > (int16_t)s_tempReportInterval || subTemp < (0 - (int16_t)s_tempReportInterval))
        ||(subHumi > (int16_t)s_humiReportInterval || subHumi < (0 - (int16_t)s_humiReportInterval))
      )
      {
         if(isregeist() == true)
          {
             setMacTransEvent(EN_TRANS_REQ_SPVN, 0x00, ADHOC_RETRY_COUNT_MAX ,LBT_REDO_COUNT_MAX); //若温湿度发生规定内的变化，立刻产生一次心跳
          }
      }//ToDo 心跳更新策略，是否更新下次心跳的时间，以省电，但破坏了时分多址的策略
  }
}
/**
 * @brief: 门磁项目while函数相关处理
 * */
void SM_process(void)
{
  feedWatchDogHandler();
  SM_key_value_handler();
  gpio_state_change_handler();

  //startReadTempHumi();//已在2s定时器内使能
  ReadShtC3();
  checkTempHumiChanged();//必须在BL55072A_DisTR()前调用
  BL55072A_DisTR();//
}


/******************get device sleep state***************************/
//true表示允许休眠
bool device_sleep_state_get(void)
{
  if(getTempHumiWorkState() || getLcdWorkFlag())
  {
    return false;
  }

  return true;
}


/**************** set tx power/ctune defaule***********************/
static void setTxpowerDefaule(void)
{
  int16_t txPowerDeciDbm = 0;
  int ret = getThisParam(RfTxPower, &txPowerDeciDbm);
  if(ret != 0) {
      txPowerDeciDbm = DEVICE_TX_POWER_DEFAULT;
      setThisParam(RfTxPower, &txPowerDeciDbm);
  }
  RAIL_Status_t status = bsp_rf_set_tx_power_bdm(txPowerDeciDbm);
  if (status != RAIL_STATUS_NO_ERROR) {
      DS_app_log_error("set tx power error, status = 0x%x\r\n", status);
  }
}

static void setCtuneDefaule(void)
{
  uint32_t ctune = 0;
  int ret = getThisParam(RfCtune, &ctune);
  if(ret != 0) {
      ctune = DEVICE_CTUNE_DEFAULT;
      setThisParam(RfCtune, &ctune);
  }
  RAIL_Status_t status = bsp_rf_set_ctune(ctune);
  if (status != RAIL_STATUS_NO_ERROR) {
      DS_app_log_error("set ctune error, status = 0x%x\r\n", status);
  }
}

static void setLfxoCtuneDefaule(void)
{
  uint8_t ctune = 0;
  int ret = getThisParam(lfxoCtune, &ctune);
  if(ret != 0) {
      ctune = DEVICE_LFXO_CTUNE_DEFAULT;
      setThisParam(lfxoCtune, &ctune);
  }

  CMU_OscillatorTuningSet(cmuOsc_LFXO,ctune); //修改，1027.仅更新ctune值，不重新初始化LFXO 以节省时间
}

/************************button handler****************************/

static struct Button btn;
static MultiTimer buttonTimer = {.Handle = 0};  //注册
static void ds_btn_state_change_callback(uint8_t intNo, void *ctx);

static ds_button_t button = {
    .port = gpioPortA,
    .pin = 5,
    .mode = gpioModeInputPull,
    .initial = 1,
    .valid = 0,
    .ds_button_state_change = ds_btn_state_change_callback,   //注册
};

/**
 * @brief: button timer callback,每10ms轮询一次button状态
 * */
static void buttonTimerCallback(MultiTimer* timer, void *userData)
{
  (void)userData;

  if(timer->Handle == 0) {
      button_handler(&btn);
  }
}

static void ds_btn_state_change_callback(uint8_t intNo, void *ctx)
{
  (void)intNo;
  ds_button_t *btnDrive = (ds_button_t *)ctx;

  if(btnDrive->port == button.port && btnDrive->pin == button.pin && buttonTimer.status == EN_MULTITIMER_STATUS_IDLE) {
      button_handler(&btn);
  }
}

/**
 * @brief: 读取button引脚状态
 * @param： button id
 * @return： gpio 状态
 * */
static uint8_t read_button_GPIO(uint8_t button_id)
{
  // you can share the GPIO read function with multiple Buttons
  switch(button_id)
  {
    case 0:
      return read_button_level(&button);
      break;
    default:
      return 0;
      break;
  }
}

//注册结果轮询？
static MultiTimer commissionTimer = {.Handle = 0};
static void commissionCallback(MultiTimer* timer, void *userData)
{
  static uint8_t count = 0;
  (void)userData;
  keyValue_t KeyValue =  {0x00,};

  count ++;
  if(EN_MSG_STATUS_JOIN_CONFIRM_SUCCESS == get_register_status()) {
      clear_register_status();
      count = 0;
      //注册成功指示,和失败一样，停止注册过程图标即可
      //LcdRegistFinish(true);
      LcdRegistFinish(false);

      KeyValue.id = 0x50;
      memcpy(KeyValue.value, s_option, 3);
      KeyValue.valueSize = 3;
      set_key_value(&KeyValue);
      KeyValue.id = 0x12;
      KeyValue.valueSize = device_TempHumi_get(KeyValue.value);
      set_key_value(&KeyValue);//注册成功，上报当前配置 add240322，以适配本地的修改
      //LcdRssiLevelSet(4);//已注册状态，显示 1130不再虚假展示，直接本地展示真实值
  }
  else {
      if(count < 61)
        softwareMultiTimerStart(EN_LP_HARD_TIMER_EM3_SYS_RTC_1, timer, 1*32768, commissionCallback,NULL,0);
      else{ //注册失败
        count = 0;
        LcdRegistFinish(false);
      }
  }
  DS_app_log_info("count = %d \r\n", count);
}

bool isBattVoltageHigh(void)
{
  return true;
}

void startCommissiongJoin(commissionType_t type, deviceType_t device)
{
  (void)type;
  (void)device;
  softwareMultiTimerStart(EN_LP_HARD_TIMER_EM3_SYS_RTC_1, &commissionTimer, 32768, commissionCallback,NULL,0);
  Commissiong_join_node_paging_packet(30);
  //ToDo 注册过程指示
  LcdRegistingStart();
}

/**
 * @brief: button 1 按键按下时回调函数
 * @param：btn结构体指针
 * */
static void btn_press_handler(void* butt)
{
  Button *btn = (Button *)butt;
  keyValue_t KeyValue =  {0x00,};

  DS_app_log_info("btn id = %d event = %d \r\n", btn->button_id, btn->event);
  if(btn->button_id == 0) {
      if(btn->event == LONG_PRESS_START) {
          if(commissionTimer.status == EN_MULTITIMER_STATUS_IDLE) {
              startCommissiongJoin(buttonTrigger, other_device);
          }
      }
      else if(btn->event == SINGLE_CLICK) {
          //切换温湿度显示单位
          if(s_option[2] & 0x01){
              s_option[2] &= 0xFE;
              LcdTempUnitSet(true);
            }
          else{
              s_option[2] |= 0x01;
              LcdTempUnitSet(false);
            }

          if(isregeist()){ //已注册时 才掉电保存NVM
          setThisParam(ENpbyOption, s_option); //是否非常耗时？
          }

          KeyValue.id = 0x50;
          memcpy(KeyValue.value, s_option, 3);
          KeyValue.valueSize = 3;
          set_key_value(&KeyValue);

          KeyValue.id = 0x12;
          KeyValue.valueSize = device_TempHumi_get(KeyValue.value);
          set_key_value(&KeyValue);

          if(false == device_test_sleep_state_get()) {
              DS_app_log_error("reg btn test \r\n");
          }
      }
  }
}

static void gpio_state_change_handler(void)
{
  if(read_button_level(&button) == button.valid) {
      if(buttonTimer.status == EN_MULTITIMER_STATUS_IDLE) {
          button_handler(&btn);
      }
  }
}

/**
 * @brief: button reed初始化；注册不同状态相关回调函数
 * */
static void SM_button_init(void)
{
  ds_button_init(&button);

  button_init(&btn, &buttonTimer, buttonTimerCallback, read_button_GPIO, button.valid, 0);
  button_attach(&btn, LONG_PRESS_START, btn_press_handler);
  button_attach(&btn, SINGLE_CLICK, btn_press_handler);
}

/**
 * @brief: led闪烁开始
 * @param： led物模型
 * */
void SM_led_start(uint8_t *data, blinkType_t type)
{
  (void)data;
  (void)type;
  //led_driver_init(&ledDriver, &ledTimer, led[0], led[1], led[2], data);
}

/*******************battery detect***************************/

static ds_gpio_t batteryGpio = {
      .port = gpioPortD,
      .pin = 2,
      .mode = gpioModePushPull,
      .initial = 0,
      .valid = 1, //温湿度硬件原理图为高电平有效
};

static MultiTimer iadcTimer;
static uint8_t adcState = 0x00;

static void iadcTimerCallback(MultiTimer* timer, void *userData)
{
  uint16_t temp16;
  (void)timer;
  (void)userData;

  if(adcState == 0) {
      battery_detect_start(iadcPosInputPortCPin0);
      ds_gpio_off(&batteryGpio);
      adcState = 0x01;
      softwareMultiTimerStart(EN_LP_HARD_TIMER_EM3_SYS_RTC_1, &iadcTimer, 32768*IADC_TIMER_INTERVAL, iadcTimerCallback,NULL,0);
  }
  else if(adcState == 0x01) {
      adcState = 0x00;
      SM_iadc_init();
  }

  if(isLocalBattIndicate)
    {
      temp16 = get_battery_monitor_voltage();
      if(temp16 >= BAT_THRESHOLD_100)
        {
          LcdBattLevelSet(4);
        }
      else if(temp16 >= BAT_THRESHOLD_75)
        {
          LcdBattLevelSet(3);
        }
      else if(temp16 >= BAT_THRESHOLD_50)
        {
          LcdBattLevelSet(2);
        }
      else if(temp16 >= BAT_THRESHOLD_25)
        {
          LcdBattLevelSet(1);
        }
      else
        {
          LcdBattLevelSet(0);
        }
    }
}

/**
 * @brief: adc init
 * */
static void SM_iadc_init(void)
{
  ds_gpio_init(&batteryGpio);
  ds_gpio_on(&batteryGpio);
  softwareMultiTimerStart(EN_LP_HARD_TIMER_EM3_SYS_RTC_1, &iadcTimer, 3277, iadcTimerCallback,NULL,0);
}

/**
 * @brief: 获取电压值
 * @return: battery unit:mV
 * */
uint8_t SM_battery_get(void)
{
  uint16_t battery = get_battery_monitor_voltage(); //默认*4， 电阻分压1/4
  if(false == device_test_sleep_state_get()) {
      DS_app_log_error("battery = %d \r\n", battery);
  }
  return battery>2500?(battery/10 - 250):0; //温湿度偏置为250，即250-505V
}
/*******************temperature get**************************************/

/**
 * @brief: Get the internal temperature of the chip
 * @return: temperature
 * */
int8_t SM_tempDrv_get(void)
{
  float tempCelsius;
  int8_t result;

  tempCelsius = EMU_TemperatureGet();

  if (tempCelsius < INT8_MIN) {
    tempCelsius = INT8_MIN;
  } else if (tempCelsius > INT8_MAX) {
    tempCelsius = INT8_MAX;
  }

  // adding extra 0.5 before truncating to simulate rounding behavior
  result = (((int8_t) (tempCelsius + 0.5 - INT8_MIN)) + INT8_MIN);

  return result;
}

/**********************get hard information***************************/

/**
 * @brief: get hard information
 * @param: point
 * @return: value length
 * */
uint8_t get_hard_information(uint8_t *data)
{
  hardinfo_t hardInfo = {0x00};
  char psn[16] = "DJ0480N00001"; //温湿度默认序列号
  int ret = 0;

  ret = getThisParam(ENpbyKeyM, hardInfo.psn);
  if(ret != 0) {
      memcpy(hardInfo.psn, psn, sizeof(psn));
      setThisParam(ENpbyKeyM, hardInfo.psn);
  }

  ret = getThisParam(ENbyDeviceType, &hardInfo.deviceType);
  if(ret != 0) {
      hardInfo.deviceType = EN_DEVICE_TYPE_IO_TEMP_HUMI;
      setThisParam(ENbyDeviceType, &hardInfo.deviceType);
  }

  ret = getThisParam(ENbyModelType, &hardInfo.modelType);
  if(ret != 0) {
      hardInfo.modelType = 0x01;
      setThisParam(ENbyModelType, &hardInfo.modelType);
  }

  ret = getThisParam(ENbyHardType, &hardInfo.hardType);
  if(ret != 0) {
      hardInfo.hardType = 0x01;
      setThisParam(ENbyHardType, &hardInfo.hardType);
  }

  ret = getThisParam(ENpbyMacID, hardInfo.pmacID);
  if(ret != 0) {
      getMacAddr(hardInfo.pmacID);
      setThisParam(ENpbyMacID, hardInfo.pmacID);
  }

  ret = getThisParam(ENpbyRfVer, hardInfo.pRfVer);
  if(ret != 0
      || hardInfo.pRfVer[0] != MAJOR_VERSION
      || hardInfo.pRfVer[1] != MINOR_VERSION
      || hardInfo.pRfVer[2] != STAGE_VERSION) {
      hardInfo.pRfVer[0] = MAJOR_VERSION;
      hardInfo.pRfVer[1] = MINOR_VERSION;
      hardInfo.pRfVer[2] = STAGE_VERSION;
      setThisParam(ENpbyRfVer, hardInfo.pRfVer);
  }

  ret = getThisParam(ENpbySensorVer, &hardInfo.sensorVer);
  if(ret != 0
      || hardInfo.sensorVer[0] != APP_MAJOR_VERSION
      || hardInfo.sensorVer[1] != APP_MINOR_VERSION
      || hardInfo.sensorVer[2] != APP_STAGE_VERSION) {
      hardInfo.sensorVer[0] = APP_MAJOR_VERSION;
      hardInfo.sensorVer[1] = APP_MINOR_VERSION;
      hardInfo.sensorVer[2] = APP_STAGE_VERSION;
      setThisParam(ENpbySensorVer, &hardInfo.sensorVer);
  }

  memcpy(data, &hardInfo, sizeof(hardInfo));

  return sizeof(hardInfo);
}

/**********************print informatio**************************/
static void printSoftWareInformation(void)
{
  uint8_t macAddr[8] = {0x00};
  getMacAddr(macAddr);
  int16_t txPowerDeciDbm = 0;
  uint32_t ctune = 0;
  char reason[12] = {0};
  uint8_t lfxoTune= 0;
  uint8_t SNNumber[16] = {0x00};

  APP_PRINTF("\r\n*************information***************\r\n");
  uint32_t rst_cause = ds_rmu_init();
  resetToString(rst_cause, reason);
  APP_PRINTF("reset reason   : %s\r\n",reason);
  APP_PRINTF("device mac     : ");
  for(uint8_t i=0;i<7;i++){
      APP_PRINTF("%02x:", macAddr[i]);
  }
  APP_PRINTF("%02x \r\n", macAddr[7]);
  APP_PRINTF("stack version  : v%d.%d.%d \r\n", (STACK_VERSION>>16&0xFF), (STACK_VERSION>>8&0xFF),STACK_VERSION&0xFF);
  APP_PRINTF("app  version   : v%d.%d.%d \r\n", (SENSOR_VERSION>>16&0xFF), (SENSOR_VERSION>>8&0xFF),SENSOR_VERSION&0xFF);
  APP_PRINTF("git  version   : 0x%x\r\n", GIT_VERSION);
  getThisParam(ENpbyKeyM, SNNumber);
  APP_PRINTF("SN number      : %s\r\n", SNNumber);
  APP_PRINTF("device type    : 0x%02X\r\n", EN_DEVICE_TYPE_IO_TEMP_HUMI);
  printfDeviceRfFreqInfo();
  getThisParam(RfTxPower, &txPowerDeciDbm);
  APP_PRINTF("device power   : %d \r\n", txPowerDeciDbm);
  getThisParam(RfCtune, &ctune);
  APP_PRINTF("device ctune   : %ld \r\n", ctune);
  getThisParam(lfxoCtune, &lfxoTune);
  APP_PRINTF("device lfxoTune: %d \r\n", lfxoTune);
  APP_PRINTF("build app time : %s %s \r\n", __DATE__, __TIME__);
#ifdef  CONFIG_JENKINS_BUILD_NUMBER
  APP_PRINTF("jenkins build number : %d\r\n", CONFIG_JENKINS_BUILD_NUMBER);
#else
  APP_PRINTF("jenkins build number : 0\r\n");//没定义默认0
#endif
  APP_PRINTF("***************************************\r\n\r\n");
}

/***********************get model api******************************/
//无线报文上传 心跳时获取Input状态
static uint8_t device_input_output_state_get(uint8_t *buffer)
{
  buffer[0] = 0;
  buffer[1] = 0;
  return 2;
}

//无线报文上传心跳时获取温湿度
static uint8_t device_TempHumi_get(uint8_t *buffer)
{
  uint16_t temp16 = 0;

  s_lastReportTemp = getCurrentTemp();
  s_lastReportHumi = getCurrentHumi();
  temp16 = (uint16_t) ((int16_t)2000 + s_lastReportTemp);
  buffer[0] = (uint8_t) (temp16 >> 8); //大端保存
  buffer[1] = (uint8_t) temp16; //当前温度 *10 + 200℃ *10， 单位0.1℃
  buffer[2] = (uint8_t) (s_lastReportHumi >> 8); //强制转换,单位1%， Cgd1011. 在sensor版本为V0.0.2及以上时，保留小数点
  buffer[3] = (uint8_t) s_lastReportHumi;
  return 4;
}


//心跳等获取子设备状态，压入温湿度物模型0x12 tempHumi
uint8_t get_device_state(uint8_t *buffer)
{
  uint8_t data[8] = {0x00};
  uint8_t data_size = 0x00;
  uint8_t index = 0;

  buffer[index] = 0x10;
  index += 1;
  data_size = device_input_output_state_get(data);
  memcpy(&buffer[index], data, data_size);
  memset(data, 0, data_size);
  index += data_size;

  buffer[index] = 0x12;
  index += 1;
  data_size = device_TempHumi_get(data);
  memcpy(&buffer[index], data, data_size);
  index += data_size;

  return index;
}

//static uint8_t s_tempReportInterval = 5;// 0.5℃
//static uint8_t s_humiReportInterval = 50;// 5%

void recv_option_key_value_handler(uint8_t *option)
{
  //解析Option字段
  uint8_t temp8;
  if(option[0] != s_option[0] ||  option[2] != s_option[2]) {
      //[0、[2变化后NVM保存Option
      setThisParam(ENpbyOption, option);
  }
  //复制option
  memcpy(s_option, option, 3);

  //Option[0]
  //温度变化量
  switch ((option[0]>>2) & 0x07)
  {
    case 0:
      s_tempReportInterval = 5;
     break;

    case 1:
      s_tempReportInterval = 10;
     break;

    case 2:
      s_tempReportInterval = 50;
     break;

    case 3:
      s_tempReportInterval = 100;
     break;

    case 4:
    case 5:
    case 6:
    case 7:
      s_tempReportInterval = 255;// 不可能的值，即表示变化后不上报
     break;
  }
  //湿度变化量
  switch ((option[0]>>5) & 0x07)
  {
    case 0:
      s_humiReportInterval = 50;
     break;

    case 1:
      s_humiReportInterval = 100;
     break;

    case 2:
      s_humiReportInterval = 150;
     break;

    case 3:
      s_humiReportInterval = 200;
     break;

    case 4:
    case 5:
    case 6:
    case 7:
      s_humiReportInterval = 255;// 不可能的值 即表示变化后不上报
     break;
  }

  //Option[1]
  //信号强度控显
  temp8 = option[1] & 0x07;
  if(0 == temp8)
  {
      isLocalRssiIndicate = true;
  }
  else
  {
      isLocalRssiIndicate = false;
      LcdRssiLevelSet(temp8);
  }

  //电池电量格数
  temp8 = (option[1]>>3) & 0x07;
  if(0 == temp8)
  {
      isLocalBattIndicate = true;
  }
  else
  {
      isLocalBattIndicate = false;
      LcdBattLevelSet(temp8 - 1);
  }

  //Option[2]
  temp8 = option[2] & 0x01;
  if(temp8 == 0)
  {
    LcdTempUnitSet(true); //摄氏度
  }
  else
  {
    LcdTempUnitSet(false);//华氏度
  }
}


static QRFH1_t globalQrfH1 = {0};
static MultiTimer findMeTimer;

static void findMeTimerCallback(MultiTimer* timer, void *userData)
{
  (void)timer;
  (void)userData;
  //ToDo findMe关闭，超时关闭
  LCD_blink_ctrl(false);
}

void SM_device_QRF_state_Handle(QRFH1_t qrfH1, QRFH2_t qrfH2)
{
  if(qrfH2.isFM == 1) {
      //Todo FindMe开启
      LCD_blink_ctrl(true);
      softwareMultiTimerStop(EN_LP_HARD_TIMER_EM3_SYS_RTC_1, &findMeTimer,0);
      softwareMultiTimerStart(EN_LP_HARD_TIMER_EM3_SYS_RTC_1, &findMeTimer, 32768*30, findMeTimerCallback,NULL,0);
  }
  else {
      if(findMeTimer.status != EN_MULTITIMER_STATUS_IDLE)
        {
         //Todo FindMe关闭
          softwareMultiTimerStop(EN_LP_HARD_TIMER_EM3_SYS_RTC_1, &findMeTimer,0);
          LCD_blink_ctrl(false);
        }
  }

  if(qrfH2.isRSSI == 1){
      LcdRssiFlashCtrl(20);//0.5s 10s
  }
  else{
      LcdRssiFlashCtrl(0);
  }

  if(qrfH1.IOen != globalQrfH1.IOen) {
      globalQrfH1.IOen = qrfH1.IOen;
  }
}

/**********************set gpio mode default*************************/
//Todo 待重新定义
void staticPowerGpioInit(void)
{
  CMU_ClockEnable(cmuClock_GPIO, true);
  GPIO_PinModeSet(gpioPortA, 3,gpioModePushPull,1);
  GPIO_PinModeSet(gpioPortA, 4,gpioModeInputPull,0);
  GPIO_PinModeSet(gpioPortC, 0,gpioModeInput,0);
}

#endif
